package com.smile.utils;

import com.smile.exception.RequestException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * <p>Okhttp 工具类</p>
 *
 * @author hzhan
 */
@Slf4j
public final class OkHttpUtils {

    /**
     * 请求客户端
     */
    private static OkHttpClient httpClient = new OkHttpClient();


    /**
     * 媒体数据类型
     */
    private static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");


    /**
     * <p>同步获取数据 Get 返回值为封装的实体 </p>
     *
     * @param url
     * @param clazz
     * @return
     */
    public static <T> T doSynGet(String url, Class<T> clazz) {
        String result = doSynGet(url);
        return FastJsonUtils.toBean(result, clazz);
    }


    /**
     * <p>同步Get请求数据</p>
     *
     * @param url
     * @return
     */
    public static String doSynGet(String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            return execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RequestException("请求数据失败");
    }

    /**
     * <p>post请求 携带Json数据</p>
     *
     * @param url
     * @param paramsJson
     * @return
     */
    public static String doSynPost(String url, String paramsJson) {
        RequestBody body = RequestBody.create(JSON, paramsJson);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            return execute(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RequestException("请求数据失败");
    }

    /**
     * @param url
     * @param json
     * @return
     */
    public static <T> T doSynPost(String url, String json, Class<T> clazz) {
        String result = doSynPost(url, json);
        checkResult(result);
        return FastJsonUtils.toBean(result, clazz);
    }

    /**
     * <p>检查返回值是否是空</p>
     *
     * @param result
     */
    private static void checkResult(String result) {
        if (StringUtils.isBlank(result)) {
            throw new RequestException("获取数据异常");
        }
    }

    /**
     * <p>处理请求</p>
     *
     * @param request
     * @return
     * @throws IOException
     */
    private static String execute(Request request) throws IOException {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        }
        throw new RequestException("请求数据失败");
    }

}
